# -*- coding: utf-8 -*-

# from django.http import HttpResponse
import json
from django.core import serializers

from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render

from django.db.models import Q

from AchievementsModel.models import User
from AchievementsModel.models import Score
from AchievementsModel.models import ScoreDate
from AchievementsModel.models import Advice

# 登录
def login(request):
    if request.method == 'GET':
        if request.session.has_key('user'):
            del request.session['user']
        return render(request, 'admin/login.html')
    else:
        print(request.POST)
        if 'user_nick' in request.POST and 'user_pwd' in request.POST:
            if checkNickAndPwd(request, request.POST['user_nick'], request.POST['user_pwd']):
                return HttpResponseRedirect('/admin')
        return render(request, 'admin/login.html', { 'error': '用户名或密码错误'})

# 登出
def logout(request):
    if request.method == 'GET':
        if request.session.has_key('user'):
            del request.session['user']
        return HttpResponseRedirect('/admin/login')
    else:
        return HttpResponse('<h1>Not found</h1><a href="/admin">返回首页</a>')

# 首页
def index(request):
    if not request.session.has_key('user'):
        return HttpResponseRedirect('/admin/login')
    if request.method == 'GET':
        return render(request, 'admin/index.html', scoreDateData(request))
    else:
        print(request.POST['score_date'])
        result = ScoreDate.objects.filter(Q(status=1))
        if result:
            context = scoreDateData(request)
            context['error'] = "有未关闭的评测，不能开始新的评测"
            return render(request, 'admin/index.html', context)
        else:
            try:
                scoredate = ScoreDate(score_date=request.POST['score_date'], status=True)
                scoredate.save()
                return HttpResponseRedirect('/admin/index')
            except Exception as err:
                print(err)
                context = scoreDateData(request)
                context['error'] = "已经有" + request.POST['score_date'] + "的评测，不能添加新的评测"
                return render(request, 'admin/index.html', context)

# 开始测评
def startScore(request):
    if not request.session.has_key('user'):
        return HttpResponseRedirect('/admin/login')
    if request.method == 'GET':
        result = ScoreDate.objects.filter(Q(status=1))
        if result:
            context = scoreDateData(request)
            context['error'] = "有未关闭的评测，不能开始新的评测"
            return render(request, 'admin/index.html', context)
        else:
            ScoreDate.objects.filter(id=request.GET['id']).update(status=True)
            return HttpResponseRedirect('/admin/index')
    else:
        return HttpResponse('<h1>Not found</h1><a href="/admin">返回首页</a>')


# 停止评测
def stopScore(request):
    if not request.session.has_key('user'):
        return HttpResponseRedirect('/admin/login')
    if request.method == 'GET':
        ScoreDate.objects.filter(Q(status=1)).update(status=0)
        return HttpResponseRedirect('/admin/index')
    else:
        return HttpResponse('<h1>Not found</h1><a href="/admin">返回首页</a>')


def deleteScore(request):
    if not request.session.has_key('user'):
        return HttpResponseRedirect('/admin/login')
    if request.method == 'GET':
        scoredate_id = request.GET['id']
        res = ScoreDate.objects.filter(Q(id=scoredate_id)).delete()
        return HttpResponseRedirect('/admin/index')
    else:
        return HttpResponse('<h1>Not found</h1><a href="/admin">返回首页</a>')

# 用户管理
def user(request):
    if not request.session.has_key('user'):
        return HttpResponseRedirect('/admin/login')
    if request.method == 'GET':
        return render(request, 'admin/user.html', userData(request))
    else:
        return HttpResponse('<h1>Not found</h1><a href="/admin">返回首页</a>')

# 添加用户
def userAdd(request):
    if not request.session.has_key('user'):
        return HttpResponseRedirect('/admin/login')
    if request.method == 'GET':
        return render(request, 'admin/user_add.html', defaultData(request))
    else:
        print(request.POST)
        user = User(user_nick=request.POST['user_nick'].strip(), user_pwd=request.POST['user_pwd'], \
                user_sex = request.POST['user_sex'].strip(), \
                user_phone=request.POST['user_phone'].strip(), is_admin= request.POST['is_admin'], \
                    position=request.POST['position'])
        if request.POST['user_name']:
            user.user_name =request.POST['user_name'].strip()
        # if request.POST['user_sex']:
        #     user.user_sex = request.POST['user_sex']
        if request.POST['user_birth']:
            user.user_birth = request.POST['user_birth']
        # if request.POST['user_phone']:
        #     user.user_phone=request.POST['user_phone']
        user.save()
        return HttpResponseRedirect('/admin/user')

# 修改用户
def userUpdate(request):
    if not request.session.has_key('user'):
        return HttpResponseRedirect('/admin/login')
    if request.method == 'GET':
        user_id = request.GET['user_id']
        if userUpdateData(request, user_id):
            return render(request, 'admin/user_update.html', userUpdateData(request, user_id))
        else:
            return HttpResponse('<h1>Not found</h1><a href="/admin">返回首页</a>')
    else:
        print('》》》',request.POST)
        user_id = request.POST['user_id']
        user = User.objects.filter(Q(id=user_id))
        user.update(user_nick=request.POST['user_nick'].strip(), user_pwd=request.POST['user_pwd'], \
                user_sex = request.POST['user_sex'].strip(), \
                user_phone=request.POST['user_phone'].strip(), is_admin= request.POST['is_admin'], \
                    position=request.POST['position'])
        if request.POST['user_name']:
            user.update(user_name=request.POST['user_name'].strip())
        if request.POST['user_birth']:
            user.update(user_birth=request.POST['user_birth'])
        return HttpResponseRedirect('/admin/user')

# 删除用户
def userDelete(request):
    if not request.session.has_key('user'):
        return HttpResponseRedirect('/admin/login')
    if request.method == 'GET':
        user_id = request.GET['user_id']
        User.objects.filter(Q(id=user_id)).delete()
        return HttpResponseRedirect('/admin/user')
    else:
        return HttpResponse('<h1>Not found</h1><a href="/admin">返回首页</a>')

# 评分管理
def score(request):
    if not request.session.has_key('user'):
        return HttpResponseRedirect('/admin/login')
    if request.method == 'GET':
        if request.GET.get('ruser'):
            ruser = request.GET.get('ruser')
        else:
            ruser = ""
        if request.GET.get('buser'):
            buser = request.GET.get('buser')
        else:
            buser = ""
        if request.GET.get('date'):
            date = request.GET.get('date')
        else:
            date = ""
        if request.GET.get('sort'):
            sort = request.GET.get('sort')
        else:
            sort = ""
        return render(request, 'admin/score.html', scoreData(request, ruser, buser, date, sort))
    else:
        return HttpResponse('<h1>Not found</h1><a href="/admin">返回首页</a>')

# 添加评分
def scoreAdd(request):
    if not request.session.has_key('user'):
        return HttpResponseRedirect('/admin/login')
    if request.method == 'GET':
        return render(request, 'admin/score_add.html', defaultData(request))
    else:
        print(request.POST)
        addscore = Score(review_id=request.POST['review_id'].strip(), be_review_id=request.POST['be_review_id'].strip(), \
                        be_review_date=request.POST['be_review_date'].strip(), score_work=request.POST['score_work'].strip(), \
                       score_quality=request.POST['score_quality'].strip(), score_skill=request.POST['score_skill'].strip(), \
                       score_attitude=request.POST['score_attitude'].strip())
        addscore.save()
        return HttpResponseRedirect('/admin/score')

# 修改评分
def scoreUpdate(request):
    if not request.session.has_key('user'):
        return HttpResponseRedirect('/admin/login')
    if request.method == 'GET':
        score_id = request.GET['score_id']
        print('》》》', request.GET)
        if scoreUpdateData(request, score_id):
            return render(request, 'admin/score_update.html', scoreUpdateData(request, score_id))
        else:
            return HttpResponse('<h1>Not found</h1><a href="/admin">返回首页</a>')
    else:
        print('》》》', request.POST)
        score_id = request.POST['score_id']
        Score.objects.filter(Q(id=score_id)).update(review_id=request.POST['review_id'].strip(), be_review_id=request.POST['be_review_id'].strip(), \
                         be_review_date=request.POST['be_review_date'].strip(), score_work=request.POST['score_work'].strip(), \
                         score_quality=request.POST['score_quality'].strip(), score_skill=request.POST['score_skill'].strip(), \
                         score_attitude=request.POST['score_attitude'].strip())
        return HttpResponseRedirect('/admin/score')

# 删除评分
def scoreDelete(request):
    if not request.session.has_key('user'):
        return HttpResponseRedirect('/admin/login')
    if request.method == 'GET':
        score_id = request.GET['score_id']
        Score.objects.filter(Q(id=score_id)).delete()
        return HttpResponseRedirect('/admin/score')
    else:
        return HttpResponse('<h1>Not found</h1><a href="/admin">返回首页</a>')

# 关于我们
def help(request):
    if not request.session.has_key('user'):
        return HttpResponseRedirect('/admin/login')
    if request.method == 'GET':
        # Advice.objects.all().delete() 删除所有
        return render(request, 'admin/help.html', adviceData(request))
    else:
        return HttpResponse('<h1>Not found</h1><a href="/admin">返回首页</a>')

def defaultData(request):
    context = {
        'user': request.session['user'],
    }
    return context

# 验证用户名密码
def checkNickAndPwd(request, nick, pwd):
    result = User.objects.filter(Q(user_nick=nick) & Q(user_pwd=pwd) & Q(is_admin=True))
    if result:
        data = serializers.serialize("json", result)
        request.session['user'] = json.loads(data)[0]
        return True
    if not User.objects.filter(Q(is_admin=True)):
        if nick == "admin" and pwd == "admin":
            request.session['user'] = {
                'pk': 0,
                'fields': {
                    'user_name': 'admin',
                    'user_nick': 'admin'
                }
            }
            return True
    return False

# 获取考核时间表数据
def scoreDateData(request):
    result = ScoreDate.objects.all()
    dataStr = serializers.serialize("json", result)
    dataJson = json.loads(dataStr)
    context = {
        'user': request.session['user'],
        'data': dataJson
    }
    # print(context)
    return context

# 获取用户表数据
def userData(request):
    result = User.objects.all()
    dataStr = serializers.serialize("json", result)
    dataJson = json.loads(dataStr)
    context = {
        'user': request.session['user'],
        'data': dataJson
    }
    # print(context)
    return context

# 获取指定id的用户
def userUpdateData(request, user_id):
    result = User.objects.filter(Q(id=user_id))
    if result:
        dataStr = serializers.serialize("json", result)
        dataJson = json.loads(dataStr)[0]
        context = {
            'user': request.session['user'],
            'data': dataJson
        }
        # print(context)
        return context
    else:
        return  {}

# 获取评分表数据
def scoreData(request, ruser, buser, date, sort):
    print('>>>>>>>', ruser, buser, date, sort)
    # print(type(buser), type(request.session["user"]["pk"]))
    # 有date查询该日期的记录
    result = Score.objects.all()
    if ruser != "":
        result = result.filter(Q(review_id=ruser))
    if buser != "":
        result = result.filter(Q(be_review_id=buser))
    if date != '':
        result = result.filter(Q(be_review_date=date))
    if sort == "0":
        # result = result.order_by("score_work")
        result = result.extra(select={'score_totol':'score_work + score_quality + score_skill + score_attitude'}).order_by('score_totol')
        # extra(select={'tag_name': 'name'})
    if sort == "1":
        # result = result.order_by("-score_work")
        result = result.extra(select={'score_totol': 'score_work + score_quality + score_skill + score_attitude'}).order_by('-score_totol')
    dataStr = serializers.serialize("json", result)
    dataJson = json.loads(dataStr)
    # print(result.query)
    # 转换类型
    try:
        ruser = int(ruser)
    except:
        ruser = ""
    try:
        buser = int(buser)
    except:
        buser = ""
    # 获取用户名
    for item in dataJson:
        user = User.objects.filter(id=item['fields']['review_id'])
        # print(item['fields']['review_id'])
        if user:
            userStr = serializers.serialize("json", user)
            userJson = json.loads(userStr)
            item['fields']['review_name'] = userJson[0]['fields']['user_name']
        else:
            item['fields']['review_name'] = item['fields']['review_id']
        user = User.objects.filter(id=item['fields']['be_review_id'])
        if user:
            userStr = serializers.serialize("json", user)
            userJson = json.loads(userStr)
            item['fields']['be_review_name'] = userJson[0]['fields']['user_name']
        else:
            item['fields']['be_review_name'] = item['fields']['be_review_id']
    # 姓名数组
    userArr = User.objects.all()
    userArrStr = serializers.serialize("json", userArr)
    userArrJson = json.loads(userArrStr)
    # print(userArrJson)
    # 选择日期数组
    dateArr = ScoreDate.objects.all()
    dateArrStr = serializers.serialize("json", dateArr)
    dateArrJson = json.loads(dateArrStr)
    context = {
        'user': request.session['user'],
        'data': dataJson,
        'date': date,
        'dateArr': dateArrJson,
        'ruser': ruser,
        'userArr': userArrJson,
        'buser': buser,
        'sort': sort,
    }
    # print(context)
    return context

# 获取指定id的评分
def scoreUpdateData(request, score_id):
    result = Score.objects.filter(Q(id=score_id))
    if result:
        dataStr = serializers.serialize("json", result)
        dataJson = json.loads(dataStr)[0]
        context = {
            'user': request.session['user'],
            'data': dataJson
        }
        return context
    else:
        return  {}

# 获取建议表数据
def adviceData(request):
    result = Advice.objects.all()
    dataStr = serializers.serialize("json", result)
    dataJson = json.loads(dataStr)
    context = {
        'user': request.session['user'],
        'data': dataJson
    }
    # print(context)
    return context




